package com.gombe.credit.app.ui.fragment

import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gombe.credit.app.R
import com.gombe.credit.app.common.CommonFragment
import com.gombe.credit.app.configs.GombeCreditApiPath
import com.gombe.credit.app.configs.GombeCreditApiUrl
import com.gombe.credit.app.configs.GombeCreditApiUrl.addCommonParams
import com.gombe.credit.app.databinding.FragmentGombeCreditStepWalletBinding
import com.gombe.credit.app.event.GombeCreditEventData
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.event.room.GombeCreditPointManager
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.ui.activity.ActGombeCreditProcessSteps
import com.gombe.credit.app.ui.adapter.AdapterGombeCreditStepWallet
import com.gombe.credit.app.ui.dialog.DialogGombeCreditWalletAdd
import com.gombe.credit.app.ui.dialog.DialogGombeCreditWalletBindOther
import com.gombe.credit.app.ui.dialog.DialogGombeCreditWalletComplete
import com.gombe.credit.app.ui.dialog.DialogGombeCreditWalletSubmitOnlyOne
import com.gombe.credit.app.ui.dialog.DialogGombeCreditWallettDelete
import com.gombe.credit.app.utils.GombeCreditDensityUtil
import com.gombe.credit.app.utils.decoration.LinearSpacingItemDecoration
import com.gombe.credit.app.utils.helper.GombeCreditConfigsHelper
import org.json.JSONObject

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/20 10:38
 * @Annotation：认证流程 - 法语地区绑定账户
 */
class FragmentGombeCreditStepWallet(): CommonFragment() {
    private var _binding: FragmentGombeCreditStepWalletBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "gombe credit step wallet binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var stepItem: JSONObject? = null
    private var eventRemark = ""

    private var walletAdapter: AdapterGombeCreditStepWallet? = null

    constructor(stepItem: JSONObject): this(){
        eventRemark = stepItem.optString("stepTitle")
        this.stepItem = stepItem
    }

    override fun takeGombeCreditRootView(inflater: LayoutInflater): View {
        _binding = FragmentGombeCreditStepWalletBinding.inflate(inflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        initGombeCreditWalletListView()

        //提交按钮在外层处理
        _binding?.walletAccountNext?.visibility = View.GONE
    }

    override fun initGombeCreditListener() {
        //添加
        _binding?.walletAccountAdd?.setOnClickListener {
            showGombeCreditWalletAddDialog()
        }

        //提交
        _binding?.walletAccountNext?.setOnClickListener {
            onGombeCreditStepWalletSubmitAction()
        }
    }

    override fun takeGombeCreditData() {
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.STEP_ACCOUNT_START)
        loadGombeCreditWalletListAction()
    }

    /**
     * 初始化Views
     */
    private fun initGombeCreditWalletListView(){
        _binding?.walletMobileListView?.isNestedScrollingEnabled = false
        _binding?.walletMobileListView?.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.walletMobileListView?.layoutManager = layoutManager
        val topDecoration = GombeCreditDensityUtil.dp2px(14f)
        _binding?.walletMobileListView?.addItemDecoration(LinearSpacingItemDecoration(0, 0, topDecoration, topDecoration))
        walletAdapter = AdapterGombeCreditStepWallet(_binding?.walletMobileListView)
        _binding?.walletMobileListView?.adapter = walletAdapter
        _binding?.walletMobileListView?.itemAnimator = DefaultItemAnimator()
        walletAdapter?.setOnItemChildClickListener { _, childView, position ->
            walletAdapter?.let {
                val item = it.getItem(position)
                when(childView.id){
                    R.id.walletEdit -> {//添加
                        showGombeCreditWalletAddDialog()
                    }
                    R.id.walletDelete -> {//删除
                        showGombeCreditWalletDeleteDialog(item)
                    }
                }
            }
        }
    }

    /**
     * 已绑定账户列表
     */
    private fun showGombeCreditWalletList(accountList: ArrayList<JSONObject>) {
        walletAdapter?.data = accountList

        walletAdapter?.let {
            //最多添加10个账户
            _binding?.walletAccountAdd?.isEnabled = it.itemCount < 10
        }
    }

    /**
     * 添加绑卡dialog
     */
    private fun showGombeCreditWalletAddDialog(){
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.USER_WALLET_ADD,eventRemark)
        val bindCardDialog = DialogGombeCreditWalletAdd(requireContext(),eventRemark,object : DialogGombeCreditWalletAdd.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                onGombeCreditWalletAddSubmitAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.setCancelable(true)
        bindCardDialog.setCanceledOnTouchOutside(false)
        bindCardDialog.show()
    }

    /**
     * 提示绑定另一个账号
     */
    fun showGombeCreditWalletOtherDialog(otherInfo: JSONObject) {
        val bindOtherDialog = DialogGombeCreditWalletBindOther(requireContext(),eventRemark,object : DialogGombeCreditWalletBindOther.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.buttonWalletOtherConfirm){//添加
                    onGombeCreditWalletAddSubmitAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                }
            }
        })
        bindOtherDialog.setCancelable(true)
        bindOtherDialog.setCanceledOnTouchOutside(false)
        bindOtherDialog.show()
        bindOtherDialog.showGombeCreditWalletInfo(otherInfo)
    }

    /**
     * 只有一个账户警告提示
     */
    private fun showGombeCreditWalletSubmitOnlyOneWarningDialog(){
        val submitOnlyOneDialog = DialogGombeCreditWalletSubmitOnlyOne(requireContext(),eventRemark,object : DialogGombeCreditWalletSubmitOnlyOne.IDialogCallback{
            override fun onClick(view: View?) {
                when(view?.id){
                    R.id.buttonWalletWarningNoMore -> {//提交(不再有账户)
                        // TODO: 发送通知，更新主流程
                        val act = getAct() as ActGombeCreditProcessSteps
                        act.showGombeCreditProcessStepSubmitSuccess()
                    }
                    R.id.buttonWalletWarningAdd -> {//继续添加
                        showGombeCreditWalletAddDialog()
                    }
                }
            }
        })
        submitOnlyOneDialog.setCancelable(true)
        submitOnlyOneDialog.setCanceledOnTouchOutside(true)
        submitOnlyOneDialog.show()
    }

    /**
     * 确认dialog
     */
    private fun showGombeCreditWalletConfirmDialog(){
        walletAdapter?.let {
            val submitDialog = DialogGombeCreditWalletComplete(requireContext(),object : DialogGombeCreditWalletComplete.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.buttonWalletAccountConfirm){
                        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.USER_WALLET_SUBMIT_TIPS_CONFIRM,"")
                        // TODO: 发送通知，更新主流程
                        val act = getAct() as ActGombeCreditProcessSteps
                        act.showGombeCreditProcessStepSubmitSuccess()
                    }
                }
            })
            submitDialog.show()
            submitDialog.showGombeCreditCompleteWalletList(it.data)
        }
    }

    /**
     * 删除提示
     */
    private fun showGombeCreditWalletDeleteDialog(item: JSONObject){
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.USER_WALLET_DELETE,item.optString("id"))
        val deleteDialog = DialogGombeCreditWallettDelete(requireContext(),eventRemark, object : DialogGombeCreditWallettDelete.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.walletAccountDeleteConfirm){
                    onGombeCreditWalletDeleteAction(item.optString("id"))
                }
            }
        })
        deleteDialog.setCancelable(true)
        deleteDialog.setCanceledOnTouchOutside(true)
        deleteDialog.show()
        deleteDialog.showGombeCreditWalletInfo(item)
    }

    /**
     * 提交按钮是否可点
     */
    private fun isGombeCreditWalletSubmit(): Boolean{
        //提交按钮是否可点
        var submitIsEnabled = false
        walletAdapter?.let {
            for (i in 0..<it.itemCount){
                //存在一个不是编辑状态的item，则可以提交
                if (!it.getItem(i).optBoolean("isEdit",true)){
                    submitIsEnabled = true
                    break
                }
            }
        }
        return submitIsEnabled
    }

    /**
     * 提交绑卡信息
     */
    private fun onGombeCreditStepWalletSubmitAction(){
        if (!isGombeCreditWalletSubmit()){
            showErrorTipsDialog(getString(R.string.gombe_credit_dialog_tips_submit_error), eventRemark)
            return
        }
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_WALLET_ACCOUNT_NEXT)
        // TODO: 进件信息点下一步 需上报所有埋点
        GombeCreditPointManager.getInstance().manualReport()

        onGombeCreditWalletCheckSubmitStatus()
    }

    /**
     * 检查提交
     */
    private fun onGombeCreditWalletCheckSubmitStatus(){
        var count = 0
        walletAdapter?.data?.forEach {
            //不是编辑类型
            if (!it.optBoolean("isEdit",true)){
                count += 1
            }
        }
        //只有一个账户，需要提示
        if (count <= 1){
            showGombeCreditWalletSubmitOnlyOneWarningDialog()
            return
        }
        //预览所有账户列表
        showGombeCreditWalletConfirmDialog()
    }

    override fun onGombeCreditPublishEvent(event: GombeCreditEventData) {
        super.onGombeCreditPublishEvent(event)
        //刷新已添加账户列表
        when(event.eventType){
            GombeCreditEventData.TYPE.GOMBECREDIT_WALLET_REFRESH -> {
                loadGombeCreditWalletListAction()
            }
            GombeCreditEventData.TYPE.GOMBECREDIT_NET_ERROR -> {
                hideGombeCreditLoading()
            }
            GombeCreditEventData.TYPE.GOMBECREDIT_PROCESS_STEP_SUBMIT -> {
                onGombeCreditStepWalletSubmitAction()
            }
            else ->{

            }
        }
    }

    /**
     * 获取已绑定的账户列表
     */
    private fun loadGombeCreditWalletListAction() {
        showGombeCreditLoading()
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_ACCOUNT_LIST_FRENCH_PATH)
        }
        doPostAction(httpUrl, params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val array = data.optJSONArray("obj")
                val accountList = arrayListOf<JSONObject>()

                if (array != null && array.length() > 0) {
                    for (i in 0..<array.length()) {
                        val item = array.optJSONObject(i)
                        item.put("isEdit", false)
                        accountList.add(item)
                    }
                }

                if (accountList.size < 2) {
                    for (i in 0..<2 - accountList.size) {
                        val item = JSONObject()
                        item.put("isEdit", true)
                        accountList.add(item)
                    }
                }
                showGombeCreditWalletList(accountList)
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    /**
     * 添加绑卡
     */
    private fun onGombeCreditWalletAddSubmitAction(mobile: String, walletChannel: String, bindFlag:String = "NO"){
        showGombeCreditLoading()
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_ACCOUNT_ADD_PATH)
            put("walletMobile", mobile)
            put("walletMobileConfirm", mobile)
            put("walletChannel", walletChannel)
            put("addBindFlag", bindFlag)
        }

        doPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                //刷新列表
                loadGombeCreditWalletListAction()
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj") ?: JSONObject()
                        // "YES/NO 是否需要提示用户这个号码可以绑另一个渠道的钱包"
                        val addBindFlag = obj.optString("addBindFlag")
                        if (addBindFlag == "YES") {
                            //需要提示绑定另一个渠道账户
                            var otherAccountInfo: JSONObject? = null

                            //用于从APP配置中获取（walletChannels）对应的信息
                            val channel = obj.optString("channel")
                            if (channel.isNotBlank()) {
                                val customize = GombeCreditConfigsHelper.takeGombeCreditConfigData()
                                if (customize != null) {
                                    val walletChannels = customize.optJSONArray("walletChannels")
                                    if (walletChannels != null && walletChannels.length() > 0) {
                                        for (i in 0..<walletChannels.length()) {
                                            val item = walletChannels.optJSONObject(i)
                                            if (channel == item.optString("value")) {
                                                otherAccountInfo = item
                                                break
                                            }
                                        }
                                    }

                                    // 只有非空的情况下才处理
                                    if (otherAccountInfo != null) {
                                        otherAccountInfo.put("walletMobile", mobile)
                                        //提示绑定另一个渠道账户
                                        showGombeCreditWalletOtherDialog(otherAccountInfo)
                                        return
                                    }
                                }
                            }
                        } else {
                            hideGombeCreditLoading()
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        showGombeCreditToast(msg)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    /**
     * 删除账户
     */
    fun onGombeCreditWalletDeleteAction(ids: String) {
        showGombeCreditLoading()
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_ACCOUNT_DELETE_PATH)
            put("ids", ids)
        }
        doPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                //刷新列表
                loadGombeCreditWalletListAction()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.STEP_ACCOUNT_END)
    }
}